package com.dukun.mybatis;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.dukun.mybatis.entity.Student;
import com.dukun.mybatis.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * MyBatis 测试类
 *
 * author：dukun
 * date：2021/10/26
 */
public class Main {

    /**
     * 测试MyBatis的查找流程
     */
    @Test
    public void testMyBatis() {
        StudentMapper mapper = getMapper(StudentMapper.class);
        List<Student> students = mapper.selectAllStudent();
        System.out.println(students);
    }

    /**
     * 测试MyBatis的添加流程
     */
    @Test
    public void testMyBatisAdd() {
        Student student = Student.builder().name("张三").age(66).build();
        StudentMapper mapper = getMapper(StudentMapper.class);
        int result = mapper.insertStudent(student);
        System.out.println(StrUtil.format("插入了{}条数据", result));
        boolean blankIfStr = StrUtil.isBlankIfStr(null);
    }

    /**
     * 搭建环境，获得mapper的代理类
     *
     * @param clazz 需要获得代理类的接口
     * @return 接口代理类
     */
    public <T> T getMapper(Class<T> clazz) {
        String resource = "mybatis-config.xml";
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession.getMapper(clazz);
    }
}
